// pages/home/home.js
import api from '../../api/api'
import { urlObj } from '../../api/url'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceList: [],
    totalLen:0,
    currentPage: 1,
    showMore:false,
    loadingText:'...'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.getDeviceList(this.data.currentPage)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      deviceList:[],
      totalLen:0,
      currentPage: 1,
      showMore:false,
      loadingText:'...'
    })
    this.getDeviceList(1)
  },
  //刷新
  onRefresh(){
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading(); 
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({
      title: '刷新中...',
    })
    this.setData({
      deviceList: [],
      totalLen:0,
      currentPage: 1,
      showMore:false,
      loadingText:'...'
    })
    this.getDeviceList(this.data.currentPage);
  },
  onPullDownRefresh(){
    this.onRefresh()
  },
  //获取设备列表
  getDeviceList(page) {
    const params = {
      limit: 10,
      page: page
    }
    api.get(urlObj.deviceList, params).then(res => {
       //隐藏loading 提示框
       wx.hideLoading();
       //隐藏导航条加载动画
       wx.hideNavigationBarLoading();
       //停止下拉刷新
       wx.stopPullDownRefresh();
      if (res.statusCode == '200') {
        let prevData = this.data.deviceList;
        if(res.data.items) {
          let { items } = res.data;
          this.setData({
            deviceList: prevData.concat(items),
            totalLen:res.data.totalItems,
            showMore:false,
            loadingText: items.length > 0 ? '...' : '没有更多了'
          })
        }else {
          this.setData({
            deviceList: [],
            showMore:false,
            loadingText: '没有更多了'
          })
        }
       
      } else {
        console.log(res.msg)
      }
    })
  },
  handleDetail(e) {
    console.log(e)
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../detail/detail?id=${id}`
    })
  },
  onReachBottom(){
    if(this.data.currentPage > 1 && this.data.loadingText == '没有更多了') {
      return;
    } else {
      let nextPage = this.data.currentPage + 1;
      this.setData({
        currentPage: nextPage,
        showMore:true
      })
      setTimeout(()=>{
        this.getDeviceList(this.data.currentPage)
      },500)
    }
  }
})